
import { getUserInfo, login } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

export default {
  namespaced: true, // 开启命名空间
  state: {
    token: getToken(), // 从缓存中读取初始值
    userInfo: {}
  },

  mutations: {
    setToken(state, newToken) {
      state.token = newToken
      // 同步到缓存
      setToken(newToken)
    },
    removeToken(state) {
      // 删除Vuex的token
      state.token = null
      removeToken()
    },
    getUserInfo(state, newuserinfo) {
      state.userInfo = newuserinfo
    }
  },

  actions: {
    async login(context, data) {
      console.log(data)
      const token = await login(data)
      console.log(3333)
      context.commit('setToken', token)
    },
    async getUserInfo(context) {
      const resut = await getUserInfo()
      context.commit('getUserInfo', resut)
    },
    logout(context) {
      context.commit('removeToken')
      context.commit('userInfo', {})
    }
  }
}

